<%@page import="com.swt.mto.thithu.service.ResultLocalServiceUtil"%>
<%@page import="com.swt.mto.thithu.model.Result"%>
<%@page import="com.liferay.portal.util.PortalUtil"%>
<%@page import="java.net.PortUnreachableException"%>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<%@page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@page import="com.liferay.portal.kernel.util.GetterUtil"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="com.swt.mto.thithu.model.Quiz"%>
<%@page import="com.liferay.portal.kernel.util.ContextPathUtil"%>
<%@page import="com.swt.mto.thithu.model.QuizCategory"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.lang.reflect.Array"%>
<%@page import="java.util.Random"%>
<%@page import="com.swt.mto.thithu.portlet.ExamPortlet"%>
<%@page import="com.liferay.portal.kernel.language.LanguageUtil"%>
<%@page import="com.swt.mto.thithu.service.persistence.AnswerUtil"%>
<%@page import="com.swt.mto.thithu.service.AnswerLocalServiceUtil"%>
<%@page import="com.swt.mto.thithu.model.Answer"%>
<%@page import="com.swt.mto.thithu.service.QuestionLocalServiceUtil"%>
<%@page import="com.swt.mto.thithu.model.Question"%>
<%@page import="java.util.List"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<portlet:defineObjects />
<%
	/* List<Question> questions = (List<Question>) request.getAttribute("listQuestion");
	int questionCount = questions.size(); */
	long quizId = GetterUtil.getLong(request.getParameter("quizId"));
	User currentUser = PortalUtil.getUser(request);
	/* User user = td.getUser(); */
	List<Question> questions = null;
	int questionCount = 0;
	if(currentUser != null){
		questions = QuestionLocalServiceUtil.getQuestionByQuiz(quizId);
		questionCount = questions.size();%>

<style type="text/css">
	#defaultCountdown {
		width: 240px;
		height: 45px;
	}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {						
		
		var MAX_COUNTER = 60;
		var counter = null;
		var counter_interval = null;

		function setCookie(name,value,days) {
		    var expires;
		    if (days) {
		        var date = new Date();
		        date.setTime(date.getTime()+(days*24*60*60*1000));
		        expires = "; expires="+date.toGMTString();
		    }
		    else {
		        expires = "";
		    }
		    document.cookie = name+"="+value+expires+"; path=/";
		}

		function getCookie(name) {
		    var nameEQ = name + "=";
		    var ca = document.cookie.split(';');
		    for(var i=0;i < ca.length;i++) {
		        var c = ca[i];
		        while (c.charAt(0) == ' ') {
		            c = c.substring(1,c.length);
		        }
		        if (c.indexOf(nameEQ) === 0) {
		            return c.substring(nameEQ.length,c.length);
		        }
		    }
		    return null;
		}

		function deleteCookie(name) {
		    setCookie(name,"",-1);
		}

		function resetCounter() {
		    counter = MAX_COUNTER;
		}

		function stopCounter() {
		    window.clearInterval(counter_interval);
		    deleteCookie('counter');
		}

		function updateCounter() {
		    var msg = '';
		    if (counter > 0) {
		        counter -= 1;
		        var numhours = Math.floor(((counter % 31536000) % 86400) / 3600);
				var numminutes = Math.floor((((counter % 31536000) % 86400) % 3600) / 60);
				var numseconds = (((counter % 31536000) % 86400) % 3600) % 60;
		        msg = numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
		        setCookie('counter', counter, 1);
		    }
		    else {
		    	var questionCount = <%=questionCount%>;		
		    	var the_value;
				the_value = getChecklistItems();
		    	$.ajax({
					data: {user: "<%=currentUser.getUserId()%>", quiz:"<%=quizId%>", countQuestion: "<%=questionCount%>", correct: getChecklistItems() },
					url: "<portlet:resourceURL id='calculate-result' />",		
					success: function(data){
						alert("ban da tra loi dung " + the_value + "/" + questionCount);
					},
					error: function(data){
						alert("loi");
					}
				});
				
				$("input[value=\"1\"] + label").css("color","red"); //show correct answer
		        msg = "Counting finished.";
		        stopCounter();
		    }
		    var el = document.getElementById('counter');
		    if (el) {
		        el.innerHTML = msg;
		    }
		}

		function startCounter() {
		    stopCounter();
		    counter_interval = window.setInterval(updateCounter, 1000);
		}

		function init() {
		    counter = getCookie('counter');
		    if (!counter) {
		        resetCounter();
		    }
		    startCounter();
		}

		init();
		
		//click Submit button
		$("#btnSubmit").click(function(){			
			var result1, result2;
			if(getNotChecklistItems() == 0){
				result1 = "<p><%=LanguageUtil.format(pageContext, "ban-co-chac-chan-muon-hoan-thanh-khong", new Object())%></p>";
				$('#dialog-form').html(result1);
				$('#dialog-form').dialog('open');		
			}	
			else {
				result2 = "<p><%=LanguageUtil.format(pageContext, "ban-con", new Object())%> " + getNotChecklistItems() + " <%=LanguageUtil.format(pageContext, "cau-hoi-chua-hoan-thanh", new Object())%></p><br/>";
				result2 += "<p><%=LanguageUtil.format(pageContext, "ban-co-chac-chan-muon-hoan-thanh-khong", new Object())%></p>";
				$('#dialog-form').html(result2);
				$('#dialog-form').dialog('open');	
			}
		});
		
		//show dialog
		$('#dialog-form').dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				"Ok": function(){
					$.ajax({
						data: {user: "<%=currentUser.getUserId()%>", quiz:"<%=quizId%>", countQuestion: "<%=questionCount%>", correct: getChecklistItems() },
						url: "<portlet:resourceURL id='calculate-result' />",		
						success: function(data){
							$('#defaultCountdown').countdown('pause');
							liftOff();
						},
						error: function(data){
							alert("loi");
						}
					});
					$(this).dialog("close");
				},
				"Cancel": function(){
					$(this).dialog("close");
				}
			}
		});
		//countdonw
		var austDay = new Date();
		austDay = new Date(austDay.getFullYear() +1, 5 , 1);
		/* $('#defaultCountdown').countdown({until: +50}, function(event){
			var $this = $(this);
		    switch(event.type) {
		        case "seconds":
		        case "minutes":
		        case "hours":
		        case "days":
		        case "weeks":
		        case "daysLeft":
		            $this.find('p.'+event.type).html(event.value);
		            break;
		        case "finished":
		            $this.hide();
		            break;
		    }
		}); */
		var time = 60;
		//$('#defaultCountdown').countdown({until: +time,  format: 'MS', onExpiry: liftOff});
		
	});
	
	
	//
	function liftOff() { 
		var questionCount = <%=questionCount%>;		
		var the_value;
		the_value = getChecklistItems();
		$.ajax({
			data: {user: "<%=currentUser.getUserId()%>", quiz:"<%=quizId%>", countQuestion: "<%=questionCount%>", correct: getChecklistItems() },
			url: "<portlet:resourceURL id='calculate-result' />",		
			success: function(data){
				alert("ban da tra loi dung " + the_value + "/" + questionCount);
			},
			error: function(data){
				alert("loi");
			}
		});
		
		$("input[value=\"1\"] + label").css("color","red"); //show correct answer
	}
	
	
	//get list radio checked
	function getChecklistItems(){
		var result = $("input:radio:checked").get();
		var columns = $.map(result, function(element){
			if($(element).attr("value") == 1)
			return $(element).attr("value");
		});
		return columns.length;
	}
	
	function getAllChecklistItems(){
		var result = $("input:radio:checked").get();
		var columns = $.map(result, function(element){	
			return $(element).attr('value');
		});
		return columns.length;
	}
	//get list radio not check
	function getNotChecklistItems(){
		var questionCount = <%=questionCount%>;
		var listNotCheck = questionCount - getAllChecklistItems();
		return listNotCheck;
	}
	
</script>


<div id="counter"></div>
<div id="wrapResult"></div>
<div id="dialog-form" style="display: none;">
    <form>
        
    </form>
</div>

<portlet:actionURL var="calculateExamURL" name="calculateExam">
	<portlet:param name="currentUser" value="<%=String.valueOf(currentUser.getUserId()) %>"/>
	<portlet:param name="quizId" value="<%=String.valueOf(quizId) %>"/>
</portlet:actionURL>
<aui:form action="<%=calculateExamURL %>">
<%
	Random random = new Random();
	
	List<Question> questions2 = new ArrayList<Question>();
	
	do{
		int rand = random.nextInt(questions.size());
		if(!questions2.contains(questions.get(rand))){
			questions2.add(questions.get(rand));
		}
	}
	while(questions.size() > questions2.size());
	
	int i=0;
	for(Question question : questions2){
		i++;
%>
		<h3><%=LanguageUtil.format(pageContext, "cau-hoi", new Object()) + " " + i + " : " + question.getDescription() %></h3>
<%
		List<Answer> answers = AnswerLocalServiceUtil.getAnswerByQuestion(question.getQuestionId());
		List<Answer> answers2 = new ArrayList<Answer>();
		
		do{
			int rand = random.nextInt(answers.size());
			if(!answers2.contains(answers.get(rand))){
				answers2.add(answers.get(rand));
			}
		}
		while(answers.size() > answers2.size());
		
		for(Answer answer : answers2){
%>
			<input type="radio" name="answer<%=i %>" value="<%=answer.getCorrect()%>" id="<%=answer.getAnswerId() %>" >
			<label for="<%=answer.getAnswerId()%>"><%=answer.getDecription() %></label><br/>
<%			
		}
	}
%>
	<button id="btnSubmit" type="button">Submit</button>
</aui:form>
<% 
	}	
	else {
		%>
		<h3>Ban chua dang nhap, ban vui long dang nhap de thi</h3>
		<%
	}
%>

<%
	
%>
<portlet:actionURL var="getListResult" name="getListResult">
</portlet:actionURL>
<a href="<%=getListResult%>">Danh sach ket qua</a>	